/**
 * 账户系统管理
 */
class AuthManager {
    constructor() {
        this.token = localStorage.getItem('auth_token');
        this.user = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.checkAuthStatus();
    }

    bindEvents() {
        // 登录按钮
        document.getElementById('login-btn').addEventListener('click', () => {
            this.showModal('login-modal');
        });

        // 注册按钮
        document.getElementById('register-btn').addEventListener('click', () => {
            this.showModal('register-modal');
        });

        // 退出按钮
        document.getElementById('logout-btn').addEventListener('click', () => {
            this.logout();
        });

        // 模态框关闭
        document.querySelectorAll('.close, [data-modal]').forEach(element => {
            element.addEventListener('click', (e) => {
                const modalId = e.target.getAttribute('data-modal') || 
                               e.target.closest('.modal').id;
                if (modalId) {
                    this.hideModal(modalId);
                }
            });
        });

        // 点击模态框外部关闭
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.hideModal(modal.id);
                }
            });
        });

        // 登录表单提交
        document.getElementById('login-form').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });

        // 注册表单提交
        document.getElementById('register-form').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleRegister();
        });
    }

    showModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('show');
            // 清空表单
            const form = modal.querySelector('form');
            if (form) {
                form.reset();
            }
        }
    }

    hideModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('show');
        }
    }

    async handleLogin() {
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;

        if (!username || !password) {
            this.showToast('请填写用户名和密码', 'error');
            return;
        }

        try {
            const response = await fetch('/api/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                this.token = data.data.token;
                this.user = data.data.user;
                localStorage.setItem('auth_token', this.token);
                this.updateUI();
                this.hideModal('login-modal');
                this.showToast('登录成功', 'success');
            } else {
                this.showToast(data.message || '登录失败', 'error');
            }
        } catch (error) {
            console.error('Login error:', error);
            this.showToast('网络错误，请稍后重试', 'error');
        }
    }

    async handleRegister() {
        const username = document.getElementById('register-username').value;
        const email = document.getElementById('register-email').value;
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;

        if (!username || !email || !password || !confirmPassword) {
            this.showToast('请填写所有字段', 'error');
            return;
        }

        if (password !== confirmPassword) {
            this.showToast('两次输入的密码不一致', 'error');
            return;
        }

        if (password.length < 6) {
            this.showToast('密码长度至少6位', 'error');
            return;
        }

        try {
            const response = await fetch('/api/user/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    email: email,
                    password: password
                })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                this.hideModal('register-modal');
                this.showToast('注册成功，请登录', 'success');
                // 自动显示登录框
                setTimeout(() => {
                    this.showModal('login-modal');
                    document.getElementById('login-username').value = username;
                }, 1000);
            } else {
                this.showToast(data.message || '注册失败', 'error');
            }
        } catch (error) {
            console.error('Register error:', error);
            this.showToast('网络错误，请稍后重试', 'error');
        }
    }

    async logout() {
        try {
            if (this.token) {
                await fetch('/api/user/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${this.token}`,
                        'Content-Type': 'application/json',
                    }
                });
            }
        } catch (error) {
            console.error('Logout error:', error);
        }

        this.token = null;
        this.user = null;
        localStorage.removeItem('auth_token');
        this.updateUI();
        this.showToast('已退出登录', 'info');
    }

    async checkAuthStatus() {
        if (!this.token) {
            this.updateUI();
            return;
        }

        try {
            const response = await fetch('/api/user/profile', {
                headers: {
                    'Authorization': `Bearer ${this.token}`,
                    'Content-Type': 'application/json',
                }
            });

            if (response.ok) {
                const data = await response.json();
                if (data.success) {
                    this.user = data.data;
                    this.updateUI();
                    return;
                }
            }
        } catch (error) {
            console.error('Auth check error:', error);
        }

        // Token无效，清除
        this.token = null;
        this.user = null;
        localStorage.removeItem('auth_token');
        this.updateUI();
    }

    updateUI() {
        const loginBtn = document.getElementById('login-btn');
        const registerBtn = document.getElementById('register-btn');
        const userMenu = document.getElementById('user-menu');
        const usernameDisplay = document.getElementById('username-display');

        if (this.user) {
            // 已登录状态
            loginBtn.style.display = 'none';
            registerBtn.style.display = 'none';
            userMenu.style.display = 'flex';
            usernameDisplay.textContent = this.user.username;
        } else {
            // 未登录状态
            loginBtn.style.display = 'inline-block';
            registerBtn.style.display = 'inline-block';
            userMenu.style.display = 'none';
        }
    }

    showToast(message, type = 'info') {
        // 移除现有的toast
        const existingToast = document.querySelector('.toast');
        if (existingToast) {
            existingToast.remove();
        }

        // 创建新的toast
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 显示toast
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    // 获取认证头
    getAuthHeaders() {
        const headers = {
            'Content-Type': 'application/json',
        };
        
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        
        return headers;
    }

    // 检查是否已登录
    isAuthenticated() {
        return !!this.token && !!this.user;
    }

    // 获取当前用户
    getCurrentUser() {
        return this.user;
    }
}

// 全局实例
window.authManager = new AuthManager();